package de.pyranja.storage.support;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;

import javax.annotation.concurrent.ThreadSafe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Resolves to a flat set of files named after their {@link BlobID}, residing in 
 * set root directory.
 * @author Chris Borckholder
 */
@ThreadSafe
public class FlatResolver implements BlobToFile {
	/* slf4j-logger */
	private final static Logger log = LoggerFactory.getLogger(FlatResolver.class);
	// root directory
	private final File root;
	
	/**
	 * Construct by setting the root file that will be a parent of all resolved 
	 * files. The root must exist and must be a writable directory.
	 * @param root the root directory
	 * @throws IllegalAgumentException if root does not exist or is not a directory
	 * @throws NullPointerException if root is null
	 */
	public FlatResolver(final File root) {
		checkNotNull(root,"cannot use null root directory");
		checkArgument(root.isDirectory(), "root file must exist and be a directory");
		this.root = root;
	}

	/* (non-Javadoc)
	 * @see de.pyranja.storage.blobs.BlobToFile#resolve(de.pyranja.storage.BlobID)
	 */
	public File resolve(final String id) {
		final File resolved = new File(root,id);
		log.trace("resolved {} to {}", id, resolved);
		return resolved;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "FlatResolver [root=" + root + "]";
	}
}
